<template>
  <div>
    <!-- 1.创建文件选择框,不需要因为el-upload内部已经实现 -->
    <!-- 2.监听文件选择框change,去查看文档,upload组件有没有提供change事件 -->
    <el-upload
      action
      :class="{disabled: fileList.length>0 }"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="handleChange"
      :http-request="handleHttpRequest"
      :before-upload="handleBeforeUpload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress v-if="uploading" :percentage="percent" style="width:197px"></el-progress>
    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>
</template>

<script>
// 4.生成cos对象
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDSozylJelgQu9D6lCRTIsFOJJBtVwABzD',
  SecretKey: '62oPm9LMwNehXCfuwoY7YouiRzQhoyud'
})
export default {
  name: 'ImageUpload',
  components: {},
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      // fileList: [{ url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }]
      fileList: [],
      uploading: false,
      percent: 0
    }
  },
  created() {},
  mounted() {},
  methods: {
    handleBeforeUpload({ size, type }) {
      if (!['image/gif', 'image/jpeg', 'image/png'].includes(type)) {
        this.$message.error('文件类型错误')
        return false
      }
      // 1TB = 1024G
      // 1G = 1024MB
      // 1MB = 1024KB
      // 1KB = 1024B
      if (size > 5 * 1024 * 1024) {
        this.$message.error('文件太大')
        return false
      }
    },
    handleChange({ raw }, fileList) {

    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const index = this.fileList.findIndex(t => t.uid === file.uid)
      this.fileList.splice(index, 1)
    },
    handleHttpRequest({ file }) {
      this.fileList = [{ url: window.URL.createObjectURL(file) }]
      this.uploading = true
      cos.uploadFile({
        Bucket: 'rzzt-1255651667', /* 桶名称 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          console.log(progressData.percent, parseInt(progressData.percent * 100))
          this.percent = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        this.uploading = false
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          // 6.把图片结果给组件
          // this.fileList = [{ url: 'http://' + data.Location }]
          this.fileList[0].url = 'http://' + data.Location
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .disabled .el-upload--picture-card {
  display: none;
}
</style>
